/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mnstudent.presentationlayer;

import mnstudent.global.Driver;
import mnstudent.global.DriversHandler;
import mnstudent.global.SConnection;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Window;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.jdesktop.swingx.prompt.PromptSupport;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

/**
 *
 * @author Administrator
 */
public class fpnlConnection extends javax.swing.JPanel {

    private boolean ok;
    private JDialog dialog;

    private SAXParserFactory saxParserFactory;
    private SAXParser saxParser;
    private Vector model;

    private String url;
    private String drivername;
    private String host;
    private String port;
    private String databasename;
    private String username;
    private String password;
    private String others;

    private String strURL;
    private String strIntegratedSecurity;

    private boolean isChangeURL;

    private final String _FILE_CONFIG_ = "xml/connection.xml";

    /**
     * Creates new form fpnlConnection
     */
    public fpnlConnection() {
        initComponents();
        model = new Vector();
        isChangeURL = false;
        url = "";
        drivername = "";
        host = "";
        port = "";
        databasename = "";
        username = "";
        password = "";
        others = "";
        strURL = "";
        strIntegratedSecurity = "";

        LoadDriverName();
        LoadConnection();
    }

    /**
     * Load thông tin list Driver hỗi trợ driver.xml LoadDriverName()
     */
    @SuppressWarnings("unchecked")
    private void LoadDriverName() {
        try {
            saxParserFactory = SAXParserFactory.newInstance();
            saxParser = saxParserFactory.newSAXParser();
            DriversHandler handler = new DriversHandler();
            saxParser.parse(new File("xml/driver.xml"), handler);

            List<Driver> lstDriver = handler.getDrivers();
            for (Driver driver : lstDriver) {
                model.addElement(driver);
            }
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(frmMainMenu.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.cmbDriverName.setModel(new DefaultComboBoxModel(model));
        this.cmbDriverName.setRenderer(new ItemDriverRender());
    }

    /**
     * Load thông tin Connection config.xml LoadConnection()
     */
    @SuppressWarnings("unchecked")
    private void LoadConnection() {

        url = SConnection.URL;
        drivername = SConnection.DriverName;
        host = SConnection.Host;
        port = SConnection.Port;
        databasename = SConnection.DatabaseName;

        //Set Item Select Commobox
        for (int i = 0; i < model.size(); i++) {
            Driver drv = (Driver) model.get(i);
            if (drv.getURL().equals(SConnection.URL)) {
                cmbDriverName.setSelectedItem(drv);
            }
        }
        strURL = url;
        strURL = String.format(strURL, host, port, databasename);
        strURL += "%s%s";

        txtHost.setText(host);
        txtPort.setText(port);
        txtDatabase.setText(databasename);

        if (!url.equals("jdbc:sqlserver://%s:%s;databaseName=%s")) {
            username = SConnection.UserName;
            password = SConnection.Password;

            txtUserName.setText(username);
            //txtPassword.setText("******");
            PromptSupport.setPrompt("******", txtPassword);

            txtUserName.setEnabled(true);
            txtUserName.setEditable(true);

            txtPassword.setEnabled(true);
            txtPassword.setEditable(true);

            strIntegratedSecurity = ";user=%s;password=%s";

            cbIntegratedSecurity.setSelected(false);
            cbIntegratedSecurity.setEnabled(false);
        } else {

            if (!SConnection.IntegratedSecurity) {
                username = SConnection.UserName;
                password = SConnection.Password;

                txtUserName.setText(username);
                //txtPassword.setText("******");
                PromptSupport.setPrompt("******", txtPassword);

                txtUserName.setEnabled(true);
                txtUserName.setEditable(true);

                txtPassword.setEnabled(true);
                txtPassword.setEditable(true);

                strIntegratedSecurity = ";user=%s;password=%s";

                cbIntegratedSecurity.setSelected(false);
                cbIntegratedSecurity.setEnabled(true);
            } else {
                cbIntegratedSecurity.setSelected(true);
                cbIntegratedSecurity.setEnabled(true);
                strIntegratedSecurity = ";integratedSecurity=true";
            }
        }
        others = SConnection.Others.trim();
        txtOthers.setText(others);

        String temp = String.format(strURL, strIntegratedSecurity, others);
        txtJDBCURL.setText(String.format(temp, username, "******").trim());

    }

    /**
     * showDialog
     *
     * @param parent
     * @param title
     * @return
     */
    public boolean showDialog(Component parent, String title) {
        ok = false;

        Frame owner = null;
        if (parent instanceof Frame) {
            owner = (Frame) parent;
        } else {
            owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
        }

        if (dialog == null || dialog.getOwner() != owner) {
            dialog = new JDialog(owner, true);
            dialog.add(this);

            dialog.getRootPane().setDefaultButton(btnOK);
            dialog.pack();
        }

        dialog.setTitle(title);
        dialog.setLocationRelativeTo(parent);
        dialog.setVisible(true);
        return ok;
    }

    /**
     * Update lại chuỗi JDBC URL update(String... arg)
     *
     * @param arg
     */
    private void update(String... arg) {
        if (isChangeURL) {
            strURL = this.getThisURL();
        } else {
            strURL = SConnection.URL;
        }
        strURL = String.format(strURL, host, port, databasename);
        strURL += "%s%s";
        String temp = String.format(strURL, strIntegratedSecurity, others);
        txtJDBCURL.setText("");
        if (arg.length > 0) {
            txtJDBCURL.setText(String.format(temp, username, arg[0]).trim());
        } else {
            txtJDBCURL.setText(String.format(temp, username, "******").trim());
        }
    }

    /**
     * Lấy URL từ object Driver của commobox getThisURL()
     *
     * @return URL of Commobox Driver Name
     */
    private String getThisURL() {
        Object[] a = cmbDriverName.getSelectedObjects();
        Driver driver = (Driver) a[0];
        return driver.getURL();
    }

    /**
     * Lấy Driver Name từ object Driver của commobox getThisDriverName()
     *
     * @return URL of Commobox Driver Name
     */
    private String getThisDriverName() {
        Object[] a = cmbDriverName.getSelectedObjects();
        Driver driver = (Driver) a[0];
        return driver.getDriverName();
    }

    /**
     * Lưu lại config file
     *
     * @param file
     * @param _url
     * @param _drivername
     * @param _host
     * @param _port
     * @param _isintegratedsecurity
     * @param _username
     * @param _password
     * @param _databasename
     * @param _others
     * @return
     */
    public boolean write(String file,
            String _url, String _drivername, String _host,
            String _port, String _isintegratedsecurity, String _username,
            String _password, String _databasename, String _others) {
        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("connections");
            doc.appendChild(rootElement);

            // staff elements
            Element connection = doc.createElement("connection");
            rootElement.appendChild(connection);

            // set attribute to staff element
            Attr attr = doc.createAttribute("id");
            attr.setValue("1");
            connection.setAttributeNode(attr);

            // url elements
            Element Eurl = doc.createElement("url");
            Eurl.appendChild(doc.createTextNode(_url));
            connection.appendChild(Eurl);

            // drivername elements
            Element Edrivername = doc.createElement("drivername");
            Edrivername.appendChild(doc.createTextNode(_drivername));
            connection.appendChild(Edrivername);

            // host elements
            Element Ehost = doc.createElement("host");
            if (_host.equals("")) {
                Ehost.appendChild(doc.createTextNode(" "));
            } else {
                Ehost.appendChild(doc.createTextNode(_host));
            }
            connection.appendChild(Ehost);

            // port elements
            Element Eport = doc.createElement("port");
            if (_port.equals("")) {
                Eport.appendChild(doc.createTextNode(" "));
            } else {
                Eport.appendChild(doc.createTextNode(_port));
            }
            connection.appendChild(Eport);

            // isintegratedsecurity elements
            Element isintegratedsecurity = doc.createElement("isintegratedsecurity");
            isintegratedsecurity.appendChild(doc.createTextNode(_isintegratedsecurity));
            connection.appendChild(isintegratedsecurity);

            // username elements
            Element Eusername = doc.createElement("username");
            if (_username.equals("")) {
                Eusername.appendChild(doc.createTextNode(" "));
            } else {
                Eusername.appendChild(doc.createTextNode(_username));
            }
            connection.appendChild(Eusername);

            // password elements
            Element Epassword = doc.createElement("password");
            if (_password.equals("")) {
                Epassword.appendChild(doc.createTextNode(" "));
            } else {
                try {
                    Epassword.appendChild(doc.createTextNode(SConnection.aes.encrypt(_password)));
                } catch (Exception ex) {
                    Logger.getLogger(frmMainMenu.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            connection.appendChild(Epassword);

            // databasename elements
            Element Edatabasename = doc.createElement("databasename");
            if (_databasename.equals("")) {
                Edatabasename.appendChild(doc.createTextNode(" "));
            } else {
                Edatabasename.appendChild(doc.createTextNode(_databasename));
            }
            connection.appendChild(Edatabasename);

            // others elements
            Element Eothers = doc.createElement("others");
            if (_others.equals("")) {
                Eothers.appendChild(doc.createTextNode(" "));
            } else {
                Eothers.appendChild(doc.createTextNode(_others));
            }
            connection.appendChild(Eothers);

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(file));

            transformer.transform(source, result);

            return true;
        } catch (ParserConfigurationException | TransformerException pce) {
            pce.printStackTrace();
            return false;
        }
    }

    private boolean testConnection() {
        String temp = String.format(strURL, strIntegratedSecurity, others);
        String URL = String.format(temp, username, password).trim();
        //JOptionPane.showMessageDialog(this, URL);
        try {
            Class.forName(drivername);
            Connection connect = DriverManager.getConnection(URL);
            return true;
        } catch (ClassNotFoundException ex) {
            System.out.println("Không khởi động được driver");
            return false;
        } catch (SQLException ex) {
            System.out.println("Không mở được kết nối");
            return false;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblDriverName = new javax.swing.JLabel();
        cmbDriverName = new javax.swing.JComboBox();
        lblHost = new javax.swing.JLabel();
        txtHost = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtDatabase = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtOthers = new javax.swing.JTextField();
        cbIntegratedSecurity = new javax.swing.JCheckBox();
        lblUserName = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtUserName = new javax.swing.JTextField();
        txtPassword = new javax.swing.JTextField();
        lblJDBCURL = new javax.swing.JLabel();
        txtJDBCURL = new javax.swing.JTextField();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnTestConnection = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Connection Information"));

        lblDriverName.setText("Driver Name:");

        cmbDriverName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbDriverNameActionPerformed(evt);
            }
        });

        lblHost.setText("Host:");

        txtHost.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtHostKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtHostKeyReleased(evt);
            }
        });

        jLabel1.setText("Port: ");

        txtPort.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPortKeyReleased(evt);
            }
        });

        jLabel2.setText("Database:");

        txtDatabase.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtDatabaseKeyReleased(evt);
            }
        });

        jLabel3.setText("Others:");

        txtOthers.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtOthersKeyReleased(evt);
            }
        });

        cbIntegratedSecurity.setSelected(true);
        cbIntegratedSecurity.setText("Use Integrated Security");
        cbIntegratedSecurity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbIntegratedSecurityActionPerformed(evt);
            }
        });

        lblUserName.setText("User Name:");

        jLabel4.setText("Password:");

        txtUserName.setEditable(false);
        txtUserName.setEnabled(false);
        txtUserName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtUserNameKeyReleased(evt);
            }
        });

        txtPassword.setEditable(false);
        txtPassword.setEnabled(false);
        txtPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPasswordActionPerformed(evt);
            }
        });
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPasswordKeyReleased(evt);
            }
        });

        lblJDBCURL.setText("JDBC URL:");

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnTestConnection.setText("Test Connection");
        btnTestConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTestConnectionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDriverName)
                    .addComponent(lblHost)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(lblUserName)
                    .addComponent(jLabel4)
                    .addComponent(lblJDBCURL))
                .addGap(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cbIntegratedSecurity)
                    .addComponent(cmbDriverName, 0, 200, Short.MAX_VALUE)
                    .addComponent(txtHost)
                    .addComponent(txtPort)
                    .addComponent(txtDatabase)
                    .addComponent(txtOthers)
                    .addComponent(txtUserName)
                    .addComponent(txtPassword)
                    .addComponent(txtJDBCURL))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnTestConnection)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 76, Short.MAX_VALUE)
                .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDriverName)
                    .addComponent(cmbDriverName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblHost)
                    .addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbIntegratedSecurity)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblUserName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtOthers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtJDBCURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblJDBCURL))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOK)
                    .addComponent(btnCancel)
                    .addComponent(btnTestConnection))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        boolean result = this.write(_FILE_CONFIG_,
                this.getThisURL(), this.getThisDriverName(), host,
                port, Boolean.toString(cbIntegratedSecurity.isSelected()), username,
                password, databasename, others);
        if (result) {
            JOptionPane.showMessageDialog(this, "Đã lưu.");
            SConnection.load();
            //Kiểm tra kết nối sau khi thay đổi có thành công hay không
            //Nếu không thành công về màn hình Login
            if (!testConnection()) {
                //Đóng Tất cả cửa sổ
                System.gc();
                for (Window window : Window.getWindows()) {
                    window.dispose();
                }
                
                //Về Form Login
                frmLogin frm = new frmLogin();
                frm.show();
            }
            ok = true;
            dialog.setVisible(false);
        } else {
            JOptionPane.showMessageDialog(this, "Không thể lưu.");
        }
    }//GEN-LAST:event_btnOKActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        dialog.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void cbIntegratedSecurityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbIntegratedSecurityActionPerformed
        if (!cbIntegratedSecurity.isSelected()) {
            username = SConnection.UserName;
            password = SConnection.Password;

            txtUserName.setText(username);
            //txtPassword.setText("******");
            PromptSupport.setPrompt("******", txtPassword);

            txtUserName.setEnabled(true);
            txtUserName.setEditable(true);

            txtPassword.setEnabled(true);
            txtPassword.setEditable(true);

            strIntegratedSecurity = ";user=%s;password=%s";
        } else {
            username = "";
            password = "";

            txtUserName.setText(username);
            //txtPassword.setText("******");
            PromptSupport.setPrompt("******", txtPassword);

            txtUserName.setEnabled(false);
            txtUserName.setEditable(false);

            txtPassword.setEnabled(false);
            txtPassword.setEditable(false);

            strIntegratedSecurity = ";integratedSecurity=true";
        }
        update();
    }//GEN-LAST:event_cbIntegratedSecurityActionPerformed

    private void txtHostKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtHostKeyPressed

    }//GEN-LAST:event_txtHostKeyPressed

    private void txtHostKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtHostKeyReleased
        host = txtHost.getText();
        update();
    }//GEN-LAST:event_txtHostKeyReleased

    private void txtPortKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPortKeyReleased
        port = txtPort.getText();
        update();
    }//GEN-LAST:event_txtPortKeyReleased

    private void txtDatabaseKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDatabaseKeyReleased
        databasename = txtDatabase.getText();
        update();
    }//GEN-LAST:event_txtDatabaseKeyReleased

    private void txtUserNameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUserNameKeyReleased
        username = txtUserName.getText();
        update();
    }//GEN-LAST:event_txtUserNameKeyReleased

    private void txtPasswordKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyReleased
        if (txtPassword.getText().equals("")) {
            password = SConnection.Password;
            update();
        } else {
            password = txtPassword.getText();
            update(password);
        }
    }//GEN-LAST:event_txtPasswordKeyReleased

    private void txtOthersKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtOthersKeyReleased
        others = txtOthers.getText();
        update();
    }//GEN-LAST:event_txtOthersKeyReleased

    private void txtPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPasswordActionPerformed

    private void cmbDriverNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbDriverNameActionPerformed
        isChangeURL = true;
        Object[] a = cmbDriverName.getSelectedObjects();
        Driver driver = (Driver) a[0];
        if (!driver.getURL().equals("jdbc:sqlserver://%s:%s;databaseName=%s")) {
            username = SConnection.UserName;
            password = SConnection.Password;

            txtUserName.setText(username);
            //txtPassword.setText("******");
            PromptSupport.setPrompt("******", txtPassword);

            txtUserName.setEnabled(true);
            txtUserName.setEditable(true);

            txtPassword.setEnabled(true);
            txtPassword.setEditable(true);

            strIntegratedSecurity = ";user=%s;password=%s";

            cbIntegratedSecurity.setSelected(false);
            cbIntegratedSecurity.setEnabled(false);
        } else {
            cbIntegratedSecurity.setSelected(false);
            cbIntegratedSecurity.setEnabled(true);
        }

        url = driver.getURL();
        drivername = driver.getDriverName();

        update();
    }//GEN-LAST:event_cmbDriverNameActionPerformed

    private void btnTestConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestConnectionActionPerformed
        if (testConnection()) {
            JOptionPane.showMessageDialog(this, "Kết nối thành công.");
        } else {
            JOptionPane.showMessageDialog(this, "Lỗi kết nối.");
        }
    }//GEN-LAST:event_btnTestConnectionActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JButton btnTestConnection;
    private javax.swing.JCheckBox cbIntegratedSecurity;
    private javax.swing.JComboBox cmbDriverName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lblDriverName;
    private javax.swing.JLabel lblHost;
    private javax.swing.JLabel lblJDBCURL;
    private javax.swing.JLabel lblUserName;
    private javax.swing.JTextField txtDatabase;
    private javax.swing.JTextField txtHost;
    private javax.swing.JTextField txtJDBCURL;
    private javax.swing.JTextField txtOthers;
    private javax.swing.JTextField txtPassword;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables

}

class ItemDriverRender extends BasicComboBoxRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index,
                isSelected, cellHasFocus);

        if (value != null) {
            Driver item = (Driver) value;
            setText(item.getName().toUpperCase());
        }

        if (index == -1) {
            Driver item = (Driver) value;
            setText(item.getName());
        }

        return this;
    }
}
